//渠道管理员查询所有订单   
//该方法2017年7月26日 改造 目的：合并页面和ctrl
faApp.controller('NewOrderListGZCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {

  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.role=$routeParams.role;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }

  $scope.statusMap = {};

  $scope.target="";
  var hasPage = "";
  if($scope.role=='qd'){//渠道
    hasPage = 'hasPageNewOrderQDM';
    $scope.target="0";
  }else if($scope.role=='qdm'){//qdm对应渠道管理员
    hasPage = 'hasPageNewOrderQDA';
     $scope.target="1";
  }else if($scope.role=='cp'){//cp代表产品经理
    hasPage = 'hasPageNewOrderCPM';
    $scope.target="";
  }else if($scope.role=='cpm'){//cp代表产品管理员
     hasPage = 'hasPageNewOrderCPA';
     $scope.target="";
  }else if($scope.role=='cwa'){
    hasPage = 'hasPageNewOrderCWA';
    $scope.target="";
  }else if($scope.role=='cwam'){
    hasPage = 'hasPageNewOrderCWGLY';
    $scope.target="";
  }

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      if($scope.role=='qdm'){
        //渠道管理查询所有订单
        newOrderService.qdalist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='qd'){
        //渠道查询单个订单
        newOrderService.qdmlist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='cp'){
        newOrderService.cpmlist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='cpm'){
        newOrderService.cpalist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='cwa'){//查询全部的
       newOrderService.cwalist($scope.config).then(function(json) {
        $scope.list = json.orderList;
        $scope.statusMap=json.statusMap;
        $scope.pager = json.page;
        $scope.loading = false;
      });
      }else if($scope.role=='cwam'){//财务管理  查询自己的
        newOrderService.cwaglylist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }
      
    }
  }, true);
  //role 角色   m 列表条件
  $scope.ctrType=$scope.role.substr(0, 2);
 /* if($scope.role=='cwa'||$scope.role=='cwam'){
    if($scope.m=='01'||$scope.m=='05'){
       $scope.ctrType += "_wwcdd";//未完成订单
    }else if($scope.m=='02'||$scope.m=='06'){
       $scope.ctrType += "_ywcdd";//已完成
    }
  }*/
   if($scope.m=='01'||$scope.m=='05'){
   // $scope.ctrType += "_wwcdd";//未完成
    $scope.ctrType += "_wddd";//全部订单
  }
 /*  列表合并  只有一个m值
  else if($scope.m=='02'||$scope.m=='06'){
    $scope.ctrType += "_ywcdd";//已完成
  }else if($scope.m=='04'||$scope.m=='08'){
    $scope.ctrType = "ddsb";//失败
  }*/
  else if($scope.m=='03'||$scope.m=='07'){
    $scope.ctrType += "_hdfydd";//后端
  }
  else if($scope.m=='09'){
    $scope.ctrType += "_dshdd";//待审核
  }

  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.ctrType
  };

  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07",
    "target": $scope.target
  };

  newOrderService.queryOrderList($scope.fit).then(function(json) {
    $scope.orderList = json.list || [];
  });

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;
  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };
  $scope.orderStatusSelected="all";
  $scope.changeStatus = function(v) {
    $scope.config['orderSonCtrType'] = v;
    $scope.orderStatusSelected=v;
    $scope.search();
  };

  $scope.search = function(reload) {
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件
    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }

    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);
      var appendStr="?";
      if(address.indexOf("?")>-1){
        appendStr="&";
      }
      var url = address +appendStr +'m='+$scope.m+'&role='+$scope.role+ '&id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }

  $scope.toUploadPage = function(pId, oId, pType, oType,address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }
      var appendStr="?";
      if(address.indexOf("?")>-1){
        appendStr="&";
      }
      var url = address + appendStr +'k=' +$scope.m  +'&role='+$scope.role + '&pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }

  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }
    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  //分配和回收处理
  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          alert("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.managerOrder = {};

  $scope.fenpeiOrHuishou = function(t) {
    $scope.managerOrder.orderIds = $scope.chooseOrderId;
    $scope.managerOrder.ptype = "02";
    $scope.managerOrder.faids = $scope.faids;

    if (t == "1") {
      if ($scope.managerOrder.systemUserId != undefined && $scope.managerOrder.systemUserId != "" && t != "") {
        // 分配操作
        $scope.managerOrder.isConfirm = "0";
        orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json) {
          if (json.statusCode) {
            if (json.statusCode == '4001') {
              var tmp = "理财师已被分配给了不同的渠道，请确认操作！\r";
              if (json.mess != undefined) {
                angular.forEach(json.mess, function(o) {
                  tmp += "理财师" + o.uid + "已被分配给：" + o.name + ";\r";
                });
              }

              if (confirm(tmp || "理财师已被分配给了不同的渠道，请确认操作！")) {
                $scope.managerOrder.isConfirm = "1";
                orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json) {
                  if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                  } else {
                    // 操作成功！分配成功！
                    $scope.alertNextPage("分配成功！");
                    $route.reload();
                  }
                });
              }
            } else {
              alert("出错了:" + json.statusCode);
            }
          } else {
            // 操作成功！分配成功！
            $scope.alertNextPage("分配成功！");
            $route.reload();
          }
        }, function(res) {
          alert('网络状态不稳定或超时！');
        });

      } else {
        alert("请选择订单跟进人！");
      }
    } else if (t == '0') {

      var tmpid = "";
      angular.forEach($scope.omu.split(","), function(o, i) {
        if (i == 0) {
          tmpid = o;
        } else {
          if (o != undefined && o != "" && o != tmpid) {
            tmpid = "99";
          }
        }
      });

      if (tmpid != undefined && tmpid != "99") {
        // 回收时，订单跟进人设为空
        $scope.managerOrder.systemUserId = "";
        // 回收
        orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      } else {
        if (confirm("选择了多笔跟进人不同的订单，确认要同时回收吗！")) {
          // 回收时，订单跟进人设为空
          $scope.managerOrder.systemUserId = "";
          // 回收
          orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json) {
            if (json.statusCode) {
              alert("出错了:" + json.statusCode);
            } else {
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }
  }

  $scope.getLastSearchConfig();
  $scope.search(true);
}]);

faApp.controller('NewOrderBaseCtrl',['$scope', 'newOrderService','$location','$controller','$routeParams','$filter','sessionService',function($scope,newOrderService,$location,$controller,$routeParams,$filter,sessionService) {
  $scope.id = $routeParams.id;
  $scope.m=$routeParams.m;
  $scope.role=$routeParams.role;
  $scope.tabUrl = {};
  $scope.item ={};
  $scope.tabUrlMap = {};
  $scope.lastProductTab = sessionService.getItem('lastProductTab') || 'orderUrl'; 
  $scope.paramTabUrl=$routeParams.paramTabUrl;
  if($scope.paramTabUrl){
    $scope.lastProductTab=$scope.paramTabUrl;
  }
  newOrderService.queryOrderDetail({
    'orderId': $scope.id,
    'role':$routeParams.role
  }).then(function(json) {
    $scope.item = json.orderDetail || {};
    $scope.loading = false; 
    var oType="";
    if($scope.item.oPType=='02'){
        oType="01";
      }else if($scope.item.oPType=='03'){
        oType="02";
      }
    //需要等待获取订单信息  初始化
    $scope.tabUrlMap = {
      orderUrl : "#/neworder/neworder0815/view?hdjy="+$routeParams.hdjy+"&m="+$scope.m+'&role='+$scope.role+ '&id=' + $scope.id + '&pType=' + $scope.item.oPType,
      dataUrl : "#/order/phoUpload?head=no&k=" +$scope.m  +'&role='+$scope.role + '&pId=' + $scope.item.oProjectId + '&oId=' + $scope.id + '&pType=' + $scope.item.oPType + '&oType=' + oType,
      cpDataUrl : "#/productOrderData/edit?head=no&k=" +$scope.m  +'&role='+$scope.role + '&pId=' + $scope.item.oProjectId + '&oId=' + $scope.id + '&pType=' + $scope.item.oPType + '&oType=' + oType,
      contractUrl : "#/neworder/neworder0815/contract/view?m="+$scope.m+'&role='+$scope.role+ '&id=' + $scope.id,
    };
    //默认选择
    $scope.changeTab('orderUrl');

  });

  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    sessionService.setItem("lastProductTab",tab);
  };

  angular.element(document).ready(function(){
     console.log($(window).height());
     //设置全部高度-30
    if ($(window).height() > 300) {
      console.info("执行")
        // $scope.iframeHeight = $(window).height()-30;
        $(".orderIframe").height($(window).height()-130)
        }

  });

}]);

faApp.controller('OrderContractCtrl',['$scope', 'newOrderService','$location','$controller','$route','$routeParams','$filter','sessionService',function($scope,newOrderService,$location,$controller,$route,$routeParams,$filter,sessionService) {   
    $controller('BaseCtrl', {$scope: $scope}); 
    $scope.id = $routeParams.id;
    $scope.m=$routeParams.m;
    $scope.role=$routeParams.role;
    $scope.item ={};
    newOrderService.queryOrderContract({
      'orderId': $scope.id
    }).then(function(json) {
      $scope.item = json.dto || {};
      console.log($scope.item);
      $scope.loading = false;
    });
    $scope.orderItem = {};

    $scope.booleanInsert=false;

     newOrderService.queryOrderDetail({
      'orderId': $scope.id
    }).then(function(json) {
      $scope.orderItem = json.orderDetail || {};
      console.log($scope.orderItem);
      var oStatus=$scope.orderItem.oStatus;
      console.log(oStatus);
      $scope.booleanInsert = (oStatus!='999'&&oStatus!='888'&&oStatus!='140'&&oStatus>='130');
      
      $scope.loading = false;
    });

    $scope.save = function(v){
      //必须参数判定，订单id设置
      if($scope.form.$invalid){
        alert("请填写完整表单");
        return ;
      }
      if(v=='05'){
        //合同封面不能为空
        if($scope.item.contractCover==''||$scope.item.contractCover==undefined){
          alert("请填写完整表单");
          return ;
        }
        //合同回收 判断  寄出合同编码和回收合同编码是否一致
        if($scope.item.contractBackCode!=$scope.item.contractCode){
          alert("寄出合同编码和回收合同编码不一致");
          return ;
        }
      }
       $scope.item.contractStatus=v;
      //判断如果新增则需要判断是否为预约成功
      if(!$scope.item.id){
        //目前订单状态是否可以支持申请合同
        if(!$scope.booleanInsert){
          alert("订单预约成功后才可以申请合同");
          return ;
          
        }
      }
      $scope.item.orderId=$scope.orderItem.orderId;
      newOrderService.orderContractUpdate($scope.item).then(function(json) {
       if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("更新成功！");
          $route.reload();
        }
      });

    }

   $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.item.contractCover = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

}]);
//新订单流程详情页   不改动原有contrl
faApp.controller('NewOrderViewCtrl', ['$scope', 'newOrderService', '$location', '$controller', '$route', '$routeParams', '$filter', function($scope, newOrderService, $location, $controller, $route, $routeParams, $filter) {
  $scope.ctrlName = "NewOrderViewCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });
  $scope.hdjy=$routeParams.hdjy;//是否显示后端结佣申请
  $scope.isShowVisitLayer = false;
  $scope.isShowVisitLayer2 = false;
  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.loading = true;
  $scope.review = {
    'id': $scope.id
  };
  $scope.pType = $routeParams.pType;
  $scope.s = $routeParams.s;
  $scope.m=$routeParams.m;
  $scope.role=$routeParams.role;
  $scope.bankCardList = {};

  $scope.showEdit=false;
  $scope.clickCount=0;

  newOrderService.queryOrderDetail({
    'orderId': $scope.id,
    'role' : $scope.role
  }).then(function(json) {
    $scope.item = json.orderDetail || {};
    $scope.bankCardList = json.bankCardList;
    $scope.backList = json.backList;
    $scope.item.wanAmount = $scope.item.oAmount/10000;
    $scope.loading = false;

  });


  //审核
  $scope.isInvestigate = function(id,status) {
     var oStatus="", auditFlag="";
     var reson="审核通过";
      if(status=='yes'){
        oStatus='130';
        reson="";
        auditFlag="chengjiaojiaAudit";
      }else{
        oStatus='140';
        reson="审核未通过";
      }
      newOrderService.updateOrderStatusAndOther({
        'id': id,
        'oStatus': oStatus,
        'oCancelReason': reson,
        'auditFlag':auditFlag
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
    //渠道设置结佣打款账号
  $scope.setCommissionInformation = function(v){
    $scope.item.bankName=v.bankName;
    $scope.item.cardNumber=v.cardNumber;
    $scope.item.userName=v.userName;
  } 

  //累积增加
  $scope.clicknum = function(v){
    if(v==1){
      $scope.clickCount=1;
    }else if($scope.clickCount==3){
      $scope.showEdit=true;
    }else if(v==2&&$scope.clickCount>=1){
      $scope.clickCount+=1;
    }
    console.log($scope.clickCount);
  }
  
  //预约成功
  $scope.applySuccess = function(v) {

    if(v){
      $scope.oCName = $scope.item.oCName;
      $scope.oAmount = $scope.item.wanAmount*10000;
      $scope.uInfo = {
        'id': $scope.id,
        'oCName':$scope.oCName,
        'oAmount':$scope.oAmount,
        'oStatus': '110',
        'updateInfo':true
      };
      newOrderService.updateOrderStatusAndOther($scope.uInfo).then(function(json) {
        if (json.statusCode) {
          switch (json.statusCode){
            case '2302':alert('订单购买金额小于起购金额')
              break;
            case '2304':alert('累进金额错误')
              break;
            case  '2303':alert('订单购买金额大于预售金额')
              break;
          };
        } else {
          $route.reload();
        }
      });
      return;
    }
    $scope.oBackTransactionPrice = $scope.item.oBackTransactionPrice;


    $scope.oSellingPrice = $scope.item.oSellingPrice;
    $scope.oBackSellingPrice = $scope.item.oBackSellingPrice;

    $scope.oBackTransactionPrice = $scope.item.oBackTransactionPrice;
    $scope.oTransactionPrice = $scope.item.oTransactionPrice;
    $scope.oTransactionRebate = $scope.item.oTransactionPrice * $scope.item.oAmount / 100;
    if ($scope.item.oBackCorePrice == undefined) {
      $scope.oBackTransactionRebate = $scope.item.oTransactionRebate;
    } else {
      $scope.oBackTransactionRebate = $scope.item.oBackTransactionPrice * $scope.item.oAmount / 100;
    }

    $scope.oKnotType = $scope.item.oKnotType
    $scope.yuyuesuccess = {
      'id': $scope.id,
      'oCName':$scope.oCName,
      'oAmount':$scope.oAmount,
      'oStatus': '130',
      'oTransactionPrice': $scope.oTransactionPrice,
      'oBackTransactionPrice': $scope.oBackTransactionPrice,
      'oTransactionRebate': $scope.oTransactionRebate,
      'oBackTransactionRebate': $scope.oBackTransactionRebate,
      'oKnotType': $scope.oKnotType,
    };
    if (!$scope.form.$invalid) {
      //有没有后端，没有就不让输入，有就输入
      //是否协议价、是就不做处理，然后让流程继续往下走，如果不是就按照判断逻辑来走。
      if ($scope.item.isAgreement == '1') {
        $scope.x = $scope.selectedId
        newOrderService.updateOrderStatusAndOther($scope.yuyuesuccess).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            $route.reload();
          }
        });
      } else {
        //如果成交价大于渠道核心价的处理，不大于才能预约成功
        if ($scope.oTransactionPrice > $scope.oSellingPrice) {
          alert("成交价大于核心价，待产品经理审核");
          $scope.yuyuesuccess.oStatus = '120';//改变预约成功为审核状态
        } else if($scope.oBackTransactionPrice > $scope.oBackSellingPrice){
            alert("后端成交价大于后端核心价，待产品经理审核");
            $scope.yuyuesuccess.oStatus = '120';//改变预约成功为审核状态
        }
        $scope.x = $scope.selectedId
        newOrderService.updateOrderStatusAndOther($scope.yuyuesuccess).then(function(json) {
              if (json.statusCode) {
                alert("出错了:" + json.statusCode);
              } else {
                $route.reload();
              }
        });
      }
    }
  };
  //已寄出有效合同
  $scope.sendContract = function() {

    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '210'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };


  //确认已签约打款
  $scope.process = function(status) {
    if ($scope.form.$invalid) {
      alert("请选择结佣账号,提醒理财师绑卡!");
      return ;
    }
    if(!($scope.item.userName&&$scope.item.cardNumber&&$scope.item.bankName)){
      alert("请选择结佣账号,提醒理财师绑卡!");
      return ;
    }
    $scope.qryqydangkang = {
      'id': $scope.id,
      'oStatus': '220',
      'userName':$scope.item.userName,
      'cardNumber':$scope.item.cardNumber,
      'bankName':$scope.item.bankName 
    };
    newOrderService.updateOrderStatusAndOther($scope.qryqydangkang).then(function(json) {
      if (json.statusCode) {
        if (json.statusCode == '2006') {
          alert("还有资料未审核通过不能返佣!!!");
        } else {
          alert("出错了:" + json.statusCode);
        }
      } else {
        $route.reload();
      }
    });
  };


  //确认打款
  $scope.comfirmPay = function() {
    if(!$scope.item.flagBaoxiao){
      alert("请分类包销分销!!");
      return ;
    }

    $scope.qrdangkang = {
        'id': $scope.id,
        'oStatus': '240',
        'flagBaoxiao':  $scope.item.flagBaoxiao,
    };
    newOrderService.updateOrderStatusAndOther($scope.qrdangkang).then(function(json) {
      if (json.statusCode) {
         if(json.statusCode=='2305'){
          alert("超募，请查看是否超出本期募集规模!!!");
        }else{
           alert("出错了:" + json.statusCode);
        }
       
      } else {
        $route.reload();
      }
    });
  };

  //佣金到账
  $scope.frontRabite = function(v) {
    $scope.userName = $scope.item.userName;
    $scope.cardNumber = $scope.item.cardNumber;
    $scope.bankName = $scope.item.bankName;
    $scope.costAmount = $scope.item.costAmount;
    $scope.activityFunds = $scope.item.activityFunds;
    $scope.otherFunds = $scope.item.otherFunds;
    $scope.remark = $scope.item.remark;
    $scope.otherRemark = $scope.item.otherRemark;
    $scope.activityRemark = $scope.item.activityRemark;
    var stat="";
    var backStat="";
    if(v=='quanduan'){//前端佣金到帐
      stat='310';
    }else if(v=='houduan'){//后端佣金到帐
      backStat='311';
    }

      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    $scope.qdyjdaozhang = {
      'id': $scope.id,
      'oStatus': stat,
      'oBackStatus': backStat,
      'userName': $scope.userName,
      'bankName': $scope.bankName,
      'cardNumber': $scope.cardNumber,
      'costAmount': $scope.costAmount,
      'activityFunds': $scope.activityFunds,
      'otherFunds': $scope.otherFunds,
      'remark': $scope.remark,
      'otherRemark': $scope.otherRemark,
      'activityRemark': $scope.activityRemark,
      'costType': costType
    };
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdyjdaozhang).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  //后端佣金到账
  $scope.backRabite = function() {
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    $scope.hdyjdaozhang = {
      'id': $scope.id,
      'oBackStatus': '311',
      'costType': costType
    };
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.hdyjdaozhang).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  //前端财务结佣
  $scope.isReq = false;
  $scope.frontFinance = function(t) {
    $scope.oRebateType = t; //自提或者结佣
    if($scope.oRebateType == 2) {
      $scope.isReq = true;
    }else{
      $scope.isReq = false;
    }

    if (!$scope.form.$invalid) {
      $scope.costAmount = $scope.item.costAmount;
      $scope.activityFunds = $scope.item.activityFunds;
      $scope.otherFunds = $scope.item.otherFunds;
      $scope.remark = $scope.item.remark;
      $scope.otherRemark = $scope.item.otherRemark;
      $scope.activityRemark = $scope.item.activityRemark;
      $scope.qdcwjieyong = {
        'id': $scope.id,
        'oStatus': '320',
        'oRebateType': $scope.oRebateType,
        'costAmount': $scope.item.costAmount,
        'activityFunds': $scope.item.activityFunds,
        'otherFunds': $scope.item.otherFunds,
        'remark': $scope.item.remark,
         'otherRemark': $scope.item.otherRemark,
        'activityRemark': $scope.item.activityRemark
      };
      if($scope.item.oOwnerId) {
        $scope.qdcwjieyong.oYouDanRebateType = $scope.oRebateType;
        delete $scope.qdcwjieyong.oRebateType;
      }
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项");
    }
  };

  //原先没有成交金额，现在先确认提交成交价 querenCJJ

  $scope.querenCJJ = function() {

    if (!$scope.form.$invalid) {
      $scope.oSellingPrice = $scope.item.oSellingPrice;
      $scope.oTransactionPrice = $scope.item.oTransactionPrice;
      $scope.oTransactionRebate = $scope.item.oTransactionPrice * $scope.item.oAmount / 100;
      console.log($scope.oTransactionPrice);
      console.log($scope.oTransactionRebate);

      $scope.qdcwjieyongCJJ = {
        'id': $scope.id,
        'oTransactionPrice': $scope.oTransactionPrice,
        'oTransactionRebate': $scope.oTransactionRebate
      };


      //是否协议价、是就不做处理，然后让流程继续往下走，如果不是就按照判断逻辑来走。
      if ($scope.item.isAgreement == '1') {
        newOrderService.updateOrderStatusAndOther($scope.qdcwjieyongCJJ).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            //改变判断依据的值
            $scope.item.shiZhuFlag = '1';
            //$route.reload();
            $location.path("/neworder/caiwu/ordermanager/incomplete/view").search({
              id: $scope.id,
              s: $scope.s
            });

          }
        });
      } else {
        //如果成交价大于渠道核心价的处理，不大于才能预约成功
        if ($scope.oTransactionPrice > $scope.oSellingPrice) {
          alert("成交价大于核心价，请联系产品部相关负责人");
        } else {
          newOrderService.updateOrderStatusAndOther($scope.qdcwjieyongCJJ).then(function(json) {
            if (json.statusCode) {
              alert("出错了:" + json.statusCode);
            } else {
              //改变判断依据的值
              $scope.item.shiZhuFlag = '1';
              //$route.reload();
              $location.path("/neworder/caiwu/ordermanager/incomplete/view").search({
                id: $scope.id,
                s: $scope.s
              });

            }
          });
        }
      }
    }
  };


  //后端财务结佣
  $scope.backFinance = function(t) {
    if(!$scope.item.costAmount){
      alert("请确认结佣金额!");
      return ;
    }
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    $scope.qdcwjieyong = {
      'id': $scope.id,
      'oBackStatus': '321',
      'costAmount':$scope.item.costAmount,
      'costType': costType
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项")
    }
  };


   //渠道申请后端结佣
  $scope.applyBackFront = function() {
    if(!$scope.item.costType){
      alert("请选择费用类型");
      return ;
    }
    var amount=($scope.item.costPrice * $scope.item.oAmount / 100);
    if(!$scope.item.oBackTransactionPrice){
      $scope.item.oBackTransactionPrice=$scope.item.costPrice;
    }
    if(!$scope.item.oBackTransactionRebate){
      $scope.item.oBackTransactionRebate=amount;
    }
     $scope.qdsqjieyong = {
      'id': $scope.id,
      'oBackStatus': '241',
      'userName' : $scope.item.userName,
      'costType': $scope.item.costType,
      'costPrice': $scope.item.costPrice,
      'costAmount': amount,
      'cardNumber': $scope.item.cardNumber ,
      'oBackTransactionPrice' :$scope.item.oBackTransactionPrice,
      'oBackTransactionRebate' :$scope.item.oBackTransactionRebate,
      'bankName': $scope.item.bankName,
      'remark': $scope.item.remark 
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdsqjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项")
    }
  };

  //产品审核后端结佣申请
  $scope.checkBackFront = function(status) {
    var oBackStatus="";
     var reson="审核通过";
      if(status=='yes'){
        //原311修改为261（新增状态  需要产品填写上游结佣）
        oBackStatus='261';   
        reson="";
      }else{
        oBackStatus='231';
        reson="审核未通过";
      }
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oBackStatus': oBackStatus,
      'reson' : reson,
      'costType': costType
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //前端确认返佣
  $scope.comfirmFrontRabite = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '330'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };


  //后端确认返佣
  $scope.comfirmBackRabite = function() {
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oBackStatus': '331',
      'costType': costType,
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //结束交易  做这个结束动作时先要判断是否结佣


  $scope.closeTrade = function() {



    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '360'
    }).then(function(json) {
      if (json.statusCode) {
        if (json.statusCode == '2008') {
          alert(json.statusCode + ":后端未走完，请先结束后端操作");
        }else  if (json.statusCode == '2006') {
          alert(json.statusCode + ":报单未审核完成");
        }else  if (json.statusCode == '2012') {
          alert(json.statusCode + ":合同未回收");
        } else {
          alert("出错了:" + json.statusCode);
        }

      } else {
        $route.reload();
      }
    });
  };

  //交易结束  不需要
  $scope.tradeClose = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '370'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //提交有效合同item.receiveContractNum
  $scope.takeEffectiveContract = function() {
    $scope.id = $scope.item.id;
    $scope.receiveContractNum = $scope.item.receiveContractNum;
    $scope.oFrontContractDocument = $scope.item.oFrontContractDocument;
    $scope.qdcwjieyong = {
      'id': $scope.id,
      'oStatus': '350',
      'receiveContractNum': $scope.receiveContractNum,
      'oFrontContractDocument': $scope.oFrontContractDocument
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode == '2006') {
          alert(json.statusCode + "-还有资料未审核通过,提交合同失败");
        } else {
          $location.path("/neworder/chanping/ordermanager/effective/view").search({
            id: $scope.id
          });
        }
      });
    }
  };


  //取消订单
  $scope.cancel = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '999'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };




  //$scope.visitList = [];
  /**回访**/
  $scope.showVisitLayer2 = function() {

    $scope.isShowVisitLayer2 = true;

  }

  //预约失败
  $scope.applyFail = function() {
    //  $scope.isShowVisitLayer2 = true;
    $scope.oCancelReason = $scope.item.oCancelReason;
    if (!$scope.itll.$invalid) {
      newOrderService.updateOrderStatusAndOther({
        'id': $scope.id,
        'oStatus': '140',
        'oCancelReason': $scope.oCancelReason
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };


  $scope.isShowTransactionPrice = function(status) {
    return (status == '250') || (status == '310') || (status == '311') || (status == '312') || (status == '313') || (status == '314');
  };

  //标记为无效订单
  $scope.avail = function(status) {
    newOrderService.updateDefriendStatus({
      'id': $scope.id,
      oDefriendStatus: status
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };



  //$scope.visitList = [];
  /**回访**/
  $scope.showVisitLayer = function() {

    $scope.isShowVisitLayer = true;


  }




  //确认订单失败
  $scope.confirmFailure = function() {
    // $scope.isShowVisitLayer = true;
    $scope.oCancelReason = $scope.item.oCancelReason;
    if (!$scope.itll.$invalid) {
      $scope.orderFailcfx = {
        'id': $scope.id,
        'oStatus': '888',
        'oCancelReason': $scope.oCancelReason
      }
      newOrderService.updateOrderStatusAndOther($scope.orderFailcfx).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);